package com.jeesite.modules.utils;

import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.ServiceException;
import com.jeesite.modules.file.entity.FileEntity;
import com.jeesite.modules.oss.client.properties.MinioProperties;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

/**
 * minio工具类
 */
@Component
@Slf4j
public class MinioUtils {

    @Autowired
    private MinioProperties properties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 下载远程文件
     *
     * @param fileEntity   文件实体，必须是上传过的文件
     * @param fullFileName 文件全名，包含绝对路径
     */
    public void getRemoteFile(FileEntity fileEntity, String fullFileName) {
        String url = "";
        if (StringUtils.isNotBlank(properties.getBaseDir())) {
            url = url + properties.getBaseDir() + "/";
        }
        url = url + "fileupload/" + fileEntity.getFilePath();
        String objectName = FileUtils.path(url) + fileEntity.getFileId() + "." + fileEntity.getFileExtension();
        try (InputStream inputStream = minioClient.getObject(properties.getBucketName(), objectName)) {
            FileUtils.copyInputStreamToFile(inputStream, new File(fullFileName));
        } catch (Exception e) {
            log.error("下载minio远程文件出错!", e);
            throw new ServiceException("下载minio远程文件出错！");
        }
    }
}
